<?php
session_start();
require_once 'auth.php';

// 检查是否已登录
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    header('Location: index.php');
    exit;
}

// 初始化错误消息
$error_msg = '';

// 处理登录请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username']) && isset($_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    // 尝试登录
    $login_result = attemptLogin($username, $password);
    
    if ($login_result === true) {
        // 登录成功，重定向到主页
        $_SESSION['logged_in'] = true;
        $_SESSION['username'] = $username;
        header('Location: index.php');
        exit;
    } else {
        // 登录失败，显示错误信息
        $error_msg = $login_result;
    }
}

// 检查是否被锁定
$lock_status = checkLockStatus();
if ($lock_status !== false) {
    $error_msg = "由于多次登录失败，账户已被锁定。请在 {$lock_status} 分钟后再试。";
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Lazy Share - 登录</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <style>
        .login-container {
            width: 300px;
            margin: 100px auto;
            padding: 20px;
            background-color: #f5f5f5;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .login-btn {
            background: #00b33c;
            color: white;
            border: none;
            padding: 10px 15px;
            cursor: pointer;
            width: 100%;
        }
        .error-msg {
            color: red;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <h2>Lazy Share 登录</h2>
        
        <?php if (!empty($error_msg)): ?>
            <div class="error-msg"><?php echo $error_msg; ?></div>
        <?php endif; ?>
        
        <?php if ($lock_status === false): ?>
            <form method="post">
                <div class="form-group">
                    <label for="username">用户名:</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码:</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <button type="submit" class="login-btn">登录</button>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>
